package com.util;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JackUtil {

	public static <T> T fromJson(String jsonString, T t) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		/**
		 * TODO:当有节点时(iary)会有转换失败的情况，此部分需要完善
		 */
		return (T) mapper.readValue(jsonString, t.getClass());
	}

	public static String toJsonString(Object object) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(object);
	}
	
	public static String getCurDate() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
		String curDate = tempDate.format(now.getTime());
		return curDate;
	}
	
	public static String getCurTime() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
		String curDate = tempDate.format(now.getTime());
		return curDate;
	}
	
	public static String getCurTime2() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
		String curDate = tempDate.format(now.getTime());
		return curDate;
	}
	
	public static String getMonthDateAfter(String dataString, Integer x){
		Calendar calendar = Calendar.getInstance(); //得到日历
		Date data = String2Date(dataString);
		calendar.setTime(data);
		calendar.add(Calendar.MONTH, +x);
		Date dateAfter = calendar.getTime();
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
		return tempDate.format(dateAfter);
	}
	
	public static Date String2Date(String dateString) {
		Date date = new Date();

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date = sdf.parse(dateString);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
		}
		return date;
	}
	public static String StringFilter(String str) throws PatternSyntaxException{     
		// 只允许字母和数字
//		 String regEx  = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
//		 String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		//只过滤\/:*?"<>|特殊字符
		String regEx = "[\\\\\"/:*?<>|]";
		Pattern p = Pattern.compile(regEx);     
		Matcher m = p.matcher(str);     
		return m.replaceAll("").trim();     
	}
}
